/* eslint-disable no-unsafe-optional-chaining */
/* eslint-disable no-debugger */
/* eslint-disable @typescript-eslint/no-use-before-define */
import Editor from "@/components/Editor";
import { selectOption } from "@/services/api/module/message/config";
import { selectOption as categrayOption } from "@/services/api/module/message/categray";
import { getTemplate, save } from "@/services/api/module/message/messageTemplate";
import { getDict } from "@/services/api/module/system/dict";
import { containsPlaceholder, extractPlaceholders, matchPlaceholder } from "@/utils";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import {
	EditableProTable,
	FooterToolbar,
	PageContainer,
	ProForm,
	ProFormInstance,
	ProFormRadio,
	ProFormSelect,
	ProFormText,
	ProFormTextArea
} from "@ant-design/pro-components";
import { Card, Form, Space, message, Button } from "antd";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";

type DataSourceType = {
	id: React.Key;
	key?: string;
	value?: string;
};
const columns: ProColumns<DataSourceType>[] = [
	{
		title: "参数名",
		dataIndex: "key",
		width: "30%",
		tooltip: "例如：content",
		formItemProps: {
			rules: [
				{
					required: true,
					whitespace: true,
					message: "此项是必填项"
				},
				{
					max: 16,
					whitespace: true,
					message: "最长为 16 位"
				},
				{
					min: 6,
					whitespace: true,
					message: "最小为 6 位"
				}
			]
		}
		// readonly: true
	},
	{
		title: "参数占位值",
		key: "value",
		dataIndex: "value",
		valueType: "text",
		tooltip: "例如：{{content}}",
		formItemProps: {
			rules: [
				{
					required: true,
					whitespace: true,
					message: "此项是必填项"
				},
				{
					max: 16,
					whitespace: true,
					message: "最长为 16 位"
				},
				{
					min: 6,
					whitespace: true,
					message: "最小为 6 位"
				}
			]
		}
	},
	{
		title: "操作",
		valueType: "option",
		width: 250
	}
];
const titles = ["新增模板", "编辑模板"];
const TemplateFormPage = () => {
	const location = useLocation();
	const navigate = useNavigate();
	const [varData] = useState<DataSourceType[]>([]);
	const [editableKeys, setEditableKeys] = useState<React.Key[]>(() => varData.map((item, index) => index));
	const [title, setTitle] = useState<string>(titles[0]);
	const eidtTableRef = useRef<ActionType>();
	const formRef = useRef<ProFormInstance>();
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [configType, setConfigType] = useState<any>([]);
	const [currentConfigType, setCurrentConfigType] = useState<any>("");
	const [templateModeOptions, setTemplateModeOptions] = useState<any>([]);
	const [currentTemplateMode, setCurrentTemplateMode] = useState<any>("");
	const [messageConfigOptions, setMessageConfigOptions] = useState<any>([]);
	useEffect(() => {
		getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		getDict("sys_message_config_type").then(data => {
			setConfigType(data);
		});
		getDict("sys_message_template_mode").then(data => {
			setTemplateModeOptions(data);
		});
	}, []);
	// 获取状态
	const { state } = location;
	useEffect(() => {
		// @ts-ignore
		if (state && state?.id) {
			setTitle(titles[1]);
			// @ts-ignore
			handleRequestTemplate(state?.id);
		}
	}, [state]);

	// 请求数据
	const handleRequestTemplate = (id: any) => {
		getTemplate(id).then(res => {
			//表单赋值
			requestMessageConfig(res.data?.type);
			formRef.current?.setFieldsValue(res?.data);
			const variablies = JSON.parse(res.data?.variable);
			formRef.current?.setFieldValue("variable", variablies);
			formRef.current?.setFieldValue("configId", res?.data?.configId);
			setCurrentTemplateMode(res?.data?.mode);
			// @ts-ignore
			setEditableKeys(() => variablies.map((item, index) => index));
		});
	};

	const editorValidator = (_: any, value: any) => {
		if (value.length > 0) {
			return Promise.resolve();
		}
		return Promise.reject(new Error("Price must be greater than zero!"));
	};

	// 修改标题，输入框，需要动态创建对应的参数占位符
	// const handleChangeTitle = (value: string) => {
	// 	if (!containsPlaceholder(value)) {
	// 		return;
	// 	}
	// 	const match = matchPlaceholder(value);
	// 	// console.log("match", match, value);

	// 	eidtTableRef.current?.addEditRecord?.(
	// 		{
	// 			id: Date.now(),
	// 			key: match,
	// 			rowKey: match,
	// 			value: value
	// 		},
	// 		{
	// 			newRecordType: "dataSource",
	// 			recordKey: Date.now()
	// 		}
	// 	);
	// };
	// 请求消息配置下拉框
	const requestMessageConfig = (messagConfigTypeParam: string | undefined) => {
		selectOption({
			type: messagConfigTypeParam
		}).then((data: any) => {
			setMessageConfigOptions(data);
		});
	};

	// 修改消息类型触发
	const handeChangeConfigType = (value: string | undefined) => {
		formRef.current?.setFieldValue("configId", undefined);
		setMessageConfigOptions([]);
		requestMessageConfig(value);
		setCurrentConfigType(value);
	};

	// 离开内容输入框生成变量
	// const handleBlurContent = (value: string | undefined) => {
	// 	if (!value) {
	// 		return;
	// 	}
	// 	// @ts-ignore
	// 	const placeholderObj: Array<any> = extractPlaceholders(value, true);
	// 	// @ts-ignore
	// 	const placeholders: Array<any> = Array.from(new Set(placeholderObj?.keys));
	// 	// @ts-ignore
	// 	const placeholdersVarKeys: Array<any> = Array.from(new Set(placeholderObj?.varKeys));
	// 	// console.log(placeholderObj, placeholders);
	// 	let newPlaceholders = [] as Array<any>; // 存储新添加的占位符
	// 	// 遍历所有占位符并判断是否已经存在
	// 	for (let i = 0; i < placeholders.length; i++) {
	// 		let placeholder = placeholders[i];
	// 		// 判断占位符是否存在于编辑表格中
	// 		if (!editableKeys.some(item => item === placeholder)) {
	// 			// 添加到新占位符数组中
	// 			newPlaceholders.push({
	// 				id: Date.now(),
	// 				key: placeholder,
	// 				rowKey: placeholder,
	// 				value: placeholdersVarKeys[i]
	// 			});
	// 		}
	// 	}
	// 	newPlaceholders.forEach(item => {
	// 		setTimeout(() => {
	// 			eidtTableRef.current?.addEditRecord(item, {
	// 				newRecordType: "dataSource",
	// 				recordKey: item?.id
	// 			});
	// 		}, 0);
	// 	});
	// };
	// 处理保存模板
	const handleSaveTemplate = (values: API.System.MessageTemplateBo) => {
		const params = { ...values };
		params.variable = JSON.stringify(params.variable);
		// @ts-ignore
		if (state?.id) {
			// 修改
		} else {
			return new Promise<void>((resolve, reject) => {
				save(params)
					.then(res => {
						console.log(res);
						// @ts-ignore
						message.success(res?.msg);
						resolve();
						navigate(-1);
					})
					.catch(() => {
						reject();
					});
			});
		}
	};

	const switchTemplateConfigTye = () => {
		switch (currentConfigType) {
			case "SMS":
				return (
					<ProFormText
						width="md"
						name="signature"
						label="短信签名"
						placeholder="请输入短信签名"
						rules={[
							{
								required: true,
								message: "请输入短信签名"
							}
						]}
					/>
				);
			case "EMAIL":
				return (
					<ProFormText
						width="md"
						name="title"
						tooltip="支持变量模式：{{content}}"
						label="标题"
						placeholder="请输入标题"
						// fieldProps={{
						// 	onBlur: e => {
						// 		handleChangeTitle(e.target?.value);
						// 	}
						// }}
						rules={[
							{
								required: true,
								message: "请输入标题"
							}
						]}
					/>
				);
		}
	};

	return (
		<PageContainer
			header={{
				breadcrumb: {},
				title: title,
				onBack: () => navigate(-1)
			}}
			token={{
				paddingBlockPageContainerContent: 0,
				paddingInlinePageContainerContent: 0
			}}
		>
			<Card>
				<ProForm<API.System.MessageTemplateBo>
					formRef={formRef}
					submitter={{
						render: (_, dom) => {
							return <Space style={{ display: "flex", justifyContent: "flex-end" }}>{dom}</Space>;
						}
					}}
					onFinish={async values => handleSaveTemplate(values)}
				>
					<ProForm.Group>
						<ProFormText
							width="md"
							name="name"
							label="模板名称"
							placeholder="请输入模板名称"
							rules={[
								{
									required: true,
									message: "请输入模板名称"
								},
								{
									min: 1,
									max: 100,
									message: "模板名称长度不能超过100个字符,不得小于1"
								}
							]}
						/>
						<ProFormSelect
							width="md"
							name="categaryId"
							label="模板分类"
							fieldProps={{
								showSearch: true,
								fieldNames: { label: "name", value: "id" }
							}}
							request={async () => {
								return await categrayOption().then((data: any) => {
									return data;
								});
							}}
							placeholder="请选择模板分类"
							rules={[
								{
									required: true,
									message: "请选择模板分类"
								}
							]}
						/>
					</ProForm.Group>
					<ProForm.Group>
						<ProFormSelect
							name="type"
							key="type"
							width="md"
							colProps={{ xs: 24, md: 12, lg: 12 }}
							label="消息类型"
							valueEnum={configType}
							onChange={handeChangeConfigType}
							placeholder="请选择消息类型"
							rules={[{ required: true, message: "请选择消息类型" }]}
						/>

						<ProFormRadio.Group
							valueEnum={statusOptions}
							name="status"
							label="状态"
							radioType="button"
							initialValue={"0"}
							placeholder="请选择状态"
							rules={[
								{
									required: true,
									message: "请选择状态"
								}
							]}
						/>
					</ProForm.Group>
					<ProForm.Group>
						{/* 消息配置 */}
						<ProFormSelect
							name="configId"
							width="md"
							label="关联消息配置"
							fieldProps={{
								fieldNames: { label: "name", value: "id" }
							}}
							options={messageConfigOptions}
							placeholder="请选择消息配置"
							rules={[{ required: true, message: "请选择消息配置" }]}
						/>

						{/* 标题，邮箱才有 */}
						{switchTemplateConfigTye()}
					</ProForm.Group>
					<ProForm.Group>
						<ProFormSelect
							name="mode"
							width="md"
							label="模板类型"
							valueEnum={templateModeOptions}
							onChange={value => {
								setCurrentTemplateMode(value);
							}}
							placeholder="请选择模板类型"
							rules={[{ required: true, message: "请选择模板类型" }]}
						/>
						{currentTemplateMode === "id" && (
							<ProFormText
								width="md"
								name="templateId"
								label="模板ID"
								extra="模板ID为服务商提供的模板ID"
								placeholder="请输入模板ID"
								rules={[
									{
										required: true,
										message: "请输入模板ID"
									}
								]}
							/>
						)}
					</ProForm.Group>
					{/* 
					{currentConfigType === "EMAIL" ? (
						<Form.Item
							tooltip="尊敬的用户，您好！{{content}}。感谢您的支持！"
							extra="尊敬的用户，您好！{{content}}。感谢您的支持！"
							name="content"
							label="内容"
							valuePropName="content"
							rules={[{ required: true, message: "请输入内容", validator: editorValidator }]}
						>
							<Editor
								height={"300px"}
								onBlur={(value: string | undefined) => {
									handleBlurContent(value);
								}}
							/>
						</Form.Item>
					) : (
						<ProFormTextArea
							tooltip="尊敬的用户，您好！{{content}}。感谢您的支持！"
							extra="尊敬的用户，您好！{{content}}。感谢您的支持！"
							colProps={{ span: 24 }}
							fieldProps={{
								onBlur: event => {
									handleBlurContent(event.target.value);
								}
							}}
							name="content"
							label="模板内容"
						/>
					)} */}
					<ProFormTextArea
						extra="尊敬的用户，您好！{{content}}。感谢您的支持！"
						colProps={{ span: 24 }}
						// fieldProps={{
						// 	onBlur: event => {
						// 		handleBlurContent(event.target.value);
						// 	}
						// }}
						rules={[
							{
								required: true,
								message: "请输入模板内容"
							}
						]}
						name="content"
						label="模板内容"
					/>
					{/* {varData?.length > 0 && ( */}
					<ProForm.Item
						tooltip="该项为模板内容中提取的参数!"
						extra="该项为模板内容中提取的参数!"
						label="参数占位符"
						name="variable"
						// initialValue={varData}
						trigger="onValuesChange"
					>
						<EditableProTable<DataSourceType>
							rowKey="id"
							toolBarRender={false}
							bordered
							name="variable"
							actionRef={eidtTableRef}
							columns={columns}
							// recordCreatorProps={false}
							recordCreatorProps={{
								newRecordType: "dataSource",
								record: () => ({
									id: Date.now()
								})
							}}
							editable={{
								type: "multiple",
								editableKeys,
								onDelete: (key: any, row: any) => {
									const updatedSelectKey = [...editableKeys];
									updatedSelectKey.splice(row.index, 1); // 删除指定下标的元素
									setEditableKeys(updatedSelectKey);
									return Promise.resolve();
								},
								onChange: setEditableKeys,
								actionRender: (row, config, defaultDoms) => {
									return [defaultDoms.delete];
								}
							}}
						/>
					</ProForm.Item>
					{/* )} */}
				</ProForm>
			</Card>
		</PageContainer>
	);
};
export default TemplateFormPage;
